package jwt.service;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class JwtService {

    private final static int  expit = 60*60*24*30;
    private final static String  key = "f80e380655dc4c349d379e24c07315e0";
    public static String getToken(String userId,String phone){
        long nowtime = System.currentTimeMillis();
        long expirt = nowtime+1000L*expit;

        //         header可以不写有默认值
        //         payload 通常⽤来存放⽤⼾信息
        //         signature 是前两个合起来的签名值
        //Calendar calendar = Calendar.getInstance();
        //calendar.add(Calendar.SECOND,300);
        String sign = JWT.create()
                .withClaim("accountId","")
                .withClaim("userId", userId)
                .withClaim("phone", phone)
                .withExpiresAt(new Date(expirt))
                .withIssuedAt(new Date(nowtime))
                .sign(Algorithm.HMAC256(key));
        System.out.println("生成的密钥是"+sign);
        return sign;
    }

    public static String verifyToken(String token){
        JWTVerifier build = JWT.require(Algorithm.HMAC256(key)).build();
        try{
            DecodedJWT jwt = build.verify(token);
            System.out.println("解析正常"+",,"+jwt.getClaim("userId").asString()+"==="+jwt.getClaim("phone").asString());
        }catch (Exception e){
            System.out.println("token解析异常");
            e.printStackTrace();
        }
        return "";
    }

    public static void main(String[] args) {
        String token = getToken("0","155");

        verifyToken(token);
    }

}
